import com.baidu.aip.ocr.AipOcr;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;

public class OcrHandle {
    private static final Logger LOG = LoggerFactory.getLogger(OcrHandle.class);
    //设置APPID/AK/SK
    private static final String APP_ID = "";
    private static final String API_KEY = "";
    private static final String SECRET_KEY = "";
    // 初始化一个AipOcr
    private static AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);

    public OcrHandle(){
        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
        // 可选：设置log4j日志输出格式，若不设置，则使用默认配置
        // 也可以直接通过jvm启动参数设置此环境变量
        System.setProperty("aip.log4j.conf", "log4j.properties");
    }

    public char[] ocr(byte[] image) {
        // 调用接口
        long start = System.currentTimeMillis();
        JSONObject res = client.basicGeneral("image", new HashMap<String, String>());
        LOG.info("ocr识别花费(毫秒):"+(System.currentTimeMillis()-start));

        LOG.info(res.toString());
        JSONArray jsonArray = res.getJSONArray("words_result");
        char[] chars = new char[0];
        for (int j = 0; j < jsonArray.length(); j++) {
            JSONObject jsonObjects = jsonArray.getJSONObject(j);
            String word = jsonObjects.getString("words");
            chars = word.toCharArray();
        }
        return chars;
    }

    public static void main(String[] args) {
        CapturePictureHandle capturePictureHandle = new CapturePictureHandle();
        byte[] bytes = capturePictureHandle.capturePicture();

        OcrHandle ocrHandle = new OcrHandle();
        char[] ocr = ocrHandle.ocr(bytes);
    }
}
